package com.asen.commons.core.base.service.impl;

import com.asen.commons.core.base.domain.BaseData;
import com.asen.commons.core.base.service.BaseDataService;
import com.asen.commons.core.meta.dao.Condition;
import com.asen.commons.utils.BaseAssert;
import org.apache.commons.lang3.StringUtils;

/**
 * 基础资料Service抽象类
 *
 * @author Gary
 * @version 1.0
 * @date 2018-12-09
 */
public abstract class AbstractBaseDataServiceImpl<T extends BaseData> extends AbstractEnableBaseServiceImpl<T> implements BaseDataService<T> {

    @Override
    protected void addValidate(T model) throws Exception {
        super.addValidate(model);

        BaseAssert.notEmpty(model.getName(), "名称不能为空");
    }

    @Override
    protected void afterAdd(T model) throws Exception {
        super.afterAdd(model);

        // 缓存
        cache(model);
    }

    @Override
    protected void updateValidate(T model) throws Exception {
        super.updateValidate(model);
        BaseAssert.notEmpty(model.getName(), "名称不能为空");
    }

    @Override
    protected void afterUpdate(T model) throws Exception {
        super.afterUpdate(model);

        // 缓存
        cache(model);
    }

    @Override
    protected void afterRemove(T model) throws Exception {
        super.afterRemove(model);

        // 缓存
        cacheRemove(model);
    }

    /**
     * 缓存
     *
     * @param model
     * @throws Exception
     */
    protected void cache(T model) throws Exception {

    }

    /**
     * 缓存
     *
     * @param model
     * @throws Exception
     */
    protected void cacheRemove(T model) throws Exception {

    }

    @Override
    public T getByName(String number) throws Exception {
        Condition condition = new Condition();
        condition.equal("name", number);
        return getBy(condition);
    }

    @Override
    public void checkDupByName(Long id, String name) throws Exception {
        if (StringUtils.isEmpty(name)) {
            return;
        }

        Condition condition = new Condition();
        if (id != null && id > 0L) {
            condition.notEqual("id", id);
        }
        condition.equal("name", name);
        int count = count(condition);
        BaseAssert.check(count == 0, "名称重复");
    }

    protected void afterEnable(T model) throws Exception {
        super.afterEnable(model);
        cache(model);
    }

    protected void afterDisable(T model) throws Exception {
        super.afterDisable(model);
        cache(model);
    }
}
